//
//  XJComposeTextView.swift
//  XJWeiBO
//
//  Created by 452608533 on 16/7/26.
//  Copyright © 2016年 452608533. All rights reserved.
//

import UIKit

class XJComposeTextView: UITextView {
    //重写父类已有属性,监听变化
   override var font:UIFont?{
        didSet{
            placeholderLabel.font = font
        }
    }
    
    var placeholder :String?{
        didSet{
            placeholderLabel.text = placeholder
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置界面
    func setupUI() {
        backgroundColor = UIColor.cyanColor()
        //添加控件
        addSubview(placeholderLabel)
        //添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        
        //通过监听系统通知来得到当前textView的文字改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "valueChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    func valueChange() {
        placeholderLabel.hidden = self.hasText()
    }
    //懒加载控件
    private lazy var placeholderLabel: UILabel = {
       
        let label = UILabel()
        
        label.numberOfLines = 0
        label.textColor = UIColor.grayColor()
        return label
    }()
}
